﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Web.Extensions;
using ERPStore.QuoteCart.Repositories;

using CloudSoft.Extensions;

namespace ERPStore.QuoteCart.Repositories
{
	public class MockQuoteCartRepository : ERPStore.QuoteCart.Repositories.IQuoteCartRepository
	{
		private IList<ERPStore.QuoteCart.Repositories.Datas.QuoteCart> m_List;

		public MockQuoteCartRepository()
		{
			m_List = new List<ERPStore.QuoteCart.Repositories.Datas.QuoteCart>();
		}

		public IQueryable<ERPStore.QuoteCart.Repositories.Datas.QuoteCart> GetQuoteCartList()
		{
			return m_List.AsQueryable();
		}

		public void Save(Models.QuoteCart cart, ERPStore.Models.UserPrincipal principal)
		{
			var existing = m_List.SingleOrDefault(i => i.Code == cart.Code);
			if (existing != null)
			{
				var index = m_List.IndexOf(existing);
				existing = cart.ToQuoteCartData(principal);
				m_List[index] = existing;
			}
			else
			{
				var data = cart.ToQuoteCartData(principal);
				data.Id = m_List.Count + 1;
				m_List.Add(data);
			}
		}

		public void Remove(string cartId)
		{
			var cart = m_List.SingleOrDefault(i => i.Code == cartId);
			if (cart != null)
			{
				m_List.Remove(cart);
			}
		}

		public void ChangeCurrent(string cartId, string visitorId)
		{
			var list = m_List.Where(i => i.VisitorId == visitorId);
			if (!list.IsNullOrEmpty())
			{
				foreach (var cart in list)
				{
					if (cart.Code == cartId)
					{
						cart.CartStateId = (int)Models.CartState.CurrentQuote;
					}
					else
					{
						cart.CartStateId = (int)Models.CartState.Quote;
					}
				}
			}
		}
	}
}
